//
//  BZAudioUtility.m
//  BZFoundation
//
//  Created by 郭艺伟 on 2017/9/28.
//  Copyright © 2017年 郭艺伟. All rights reserved.
//

#import "BZAudioUtility.h"
#import <AVFoundation/AVFoundation.h>

#import "amrFileCodec.h"

NSString * const BZAudioUtilityErrorDomain = @"com.BZ.BZAudioUtilityErrorDomain";
@implementation BZAudioUtility

#pragma mark - Wav Amr Conversion

+ (BOOL)convertWavFile:(NSURL *)wavFilePath
             toAmrFile:(NSURL *)amrFilePath
                 error:(NSError *__autoreleasing *)error {
    char theErrorDescription[100] = "\0";
    
    if (!encodeWAVEFileToAMRFile(wavFilePath.path.UTF8String, amrFilePath.path.UTF8String, theErrorDescription)) {
        if (error) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:amrFilePath.path]) {
                [[NSFileManager defaultManager] removeItemAtPath:amrFilePath.path error:nil];
            }
            NSString *errorDescription = [NSString stringWithUTF8String:theErrorDescription];
            NSError *theError = [NSError errorWithDomain:BZAudioUtilityErrorDomain
                                                    code:-1
                                                userInfo:@{NSLocalizedDescriptionKey: errorDescription ?: @""}];
            *error = theError;
        }
        return NO;
    }
    return YES;
}

+ (BOOL)convertAmrFile:(NSURL *)amrFilePath
             toWavFile:(NSURL *)wavFilePath
                 error:(NSError *__autoreleasing *)error {
    char theErrorDescription[100] = "\0";
    if (!decodeAMRFileToWAVEFile(amrFilePath.path.UTF8String, wavFilePath.path.UTF8String, theErrorDescription)) {
        if (error) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:wavFilePath.path]) {
                [[NSFileManager defaultManager] removeItemAtPath:wavFilePath.path error:nil];
            }
            NSString *errorDescription = [NSString stringWithUTF8String:theErrorDescription];
            NSError *theError = [NSError errorWithDomain:BZAudioUtilityErrorDomain
                                                    code:-1
                                                userInfo:@{NSLocalizedDescriptionKey: errorDescription ?: @""}];
            *error = theError;
        }
        return NO;
    }
    return YES;
}

#pragma mark - Wav Duration

+ (NSTimeInterval)wavDurationWithFilePath:(NSURL *)filePath{
    AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:filePath options:nil];
    CMTime audioDuration = audioAsset.duration;
    NSTimeInterval audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    return audioDurationSeconds;
}


@end
